package com.lwl.blue.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwl.blue.commont.base.BizException;
import com.lwl.blue.commont.base.ErrorCode;
import com.lwl.blue.commont.base.JsonResult;
import com.lwl.blue.commont.base.PageParam;
import com.lwl.blue.commont.utils.UUIDVersionUtils;
import com.lwl.blue.dao.PurchaseOrderDao;
import com.lwl.blue.entity.PurchaseOrder;
import com.lwl.blue.service.PurchaseOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderDao, PurchaseOrder> implements PurchaseOrderService {

    @Resource
    private PurchaseOrderDao purchaseOrderDao;

    @Override
    public JsonResult<Page<PurchaseOrder>> pages(PageParam<PurchaseOrder> pageParam) {
        // 构建 MyBatis-Plus 分页对象，并委托自定义 Mapper 执行分页 SQL
        Page<PurchaseOrder> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        return new JsonResult<Page<PurchaseOrder>>().success(purchaseOrderDao.pages(page, pageParam.getParam()));
    }

    @Override
    public JsonResult<PurchaseOrder> getByPk(String id) {
        // 按主键查询单条记录，未找到时抛出统一的业务异常
        PurchaseOrder po = purchaseOrderDao.getByPk(id);
        if (po == null) {
            throw new BizException(ErrorCode.DATA_NOT_EXIST_ERROR.getCode(), ErrorCode.DATA_NOT_EXIST_ERROR.getMsg());
        }
        return new JsonResult<PurchaseOrder>().success(po);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> rejectForRevision(PurchaseOrder order, String rejectReason) {
        try {
            // 1. 生成新版本号
            String currentVersion = order.getDocVersion() != null ? order.getDocVersion() : "V1";
            String newVersion = UUIDVersionUtils.generateNextVersion(currentVersion);
            
            // 2. 为历史版本生成版本化UUID
            String historyUUID = UUIDVersionUtils.generateVersionedUUID(order.getId(), currentVersion);
            
            // 3. 创建历史版本订单（原订单的备份）
            PurchaseOrder historyOrder = new PurchaseOrder();
            copyOrderData(order, historyOrder);
            historyOrder.setId(historyUUID); // 使用版本化UUID
            historyOrder.setOrderNo(order.getOrderNo() + "_HISTORY_" + currentVersion); // 历史版本订单号
            historyOrder.setRedFlag("YES"); // 标记为历史版本
            historyOrder.setAttr1(rejectReason); // 保存驳回原因
            historyOrder.setDocVersion(currentVersion); // 保持原版本号
            
            // 4. 保存历史版本
            save(historyOrder);
            
            // 5. 更新原订单为新版本
            order.setDocVersion(newVersion);
            order.setDocStatus(11); // 状态设为驳回
            order.setRedFlag("NO"); // 新版本不是历史版本
            order.setAttr1(rejectReason); // 保存驳回原因
            updateById(order);
            
            return new JsonResult<String>().success("订单已打回重审，新版本号：" + newVersion, null);
            
        } catch (Exception e) {
            throw new BizException(ErrorCode.SYS_EXCEPTION.getCode(), "打回重审处理失败：" + e.getMessage());
        }
    }
    
    /**
     * 复制订单数据
     */
    private void copyOrderData(PurchaseOrder source, PurchaseOrder target) {
        target.setOrderNo(source.getOrderNo());
        target.setCancelInnerId(source.getCancelInnerId());
        target.setCancelNo(source.getCancelNo());
        target.setLastBizDocNo(source.getLastBizDocNo());
        target.setSignDate(source.getSignDate());
        target.setValidStartDate(source.getValidStartDate());
        target.setValidEndDate(source.getValidEndDate());
        target.setSignLocation(source.getSignLocation());
        target.setDeliveryPlanType(source.getDeliveryPlanType());
        target.setDeliveryTerms(source.getDeliveryTerms());
        target.setExpectedDeliveryDate(source.getExpectedDeliveryDate());
        target.setPickupPeriodStart(source.getPickupPeriodStart());
        target.setPickupPeriodEnd(source.getPickupPeriodEnd());
        target.setPaymentTerms(source.getPaymentTerms());
        target.setCreatorId(source.getCreatorId());
        target.setUpdaterId(source.getUpdaterId());
        target.setVersionEffectiveTime(source.getVersionEffectiveTime());
        target.setOriginalEffectiveDate(source.getOriginalEffectiveDate());
        target.setExternalCancelInnerId(source.getExternalCancelInnerId());
        target.setExternalCancelNo(source.getExternalCancelNo());
        target.setExternalSystemType(source.getExternalSystemType());
        target.setExternalDocInnerId(source.getExternalDocInnerId());
        target.setExternalDocNo(source.getExternalDocNo());
        target.setBizSource(source.getBizSource());
        target.setBizSourceDesc(source.getBizSourceDesc());
        target.setSourceDocNo(source.getSourceDocNo());
        target.setBizDocCode(source.getBizDocCode());
        target.setSupId(source.getSupId());
        target.setTotalAmount(source.getTotalAmount());
        target.setTotalTaxFreeAmount(source.getTotalTaxFreeAmount());
        target.setTaxRate(source.getTaxRate());
        target.setTaxAmount(source.getTaxAmount());
        target.setIsTempPrice(source.getIsTempPrice());
        target.setAttr1(source.getAttr1());
        target.setAttr2(source.getAttr2());
        target.setAttr3(source.getAttr3());
        target.setAttr4(source.getAttr4());
        target.setAttr5(source.getAttr5());
        target.setAttr6(source.getAttr6());
        target.setAttr7(source.getAttr7());
        target.setAttr8(source.getAttr8());
        target.setAttr9(source.getAttr9());
        target.setAttr10(source.getAttr10());
    }

    @Override
    public JsonResult<java.util.List<PurchaseOrder>> getHistoryVersions(String originalUUID) {
        try {
            // 1. 获取所有可能的历史版本UUID
            java.util.List<String> historyUUIDs = UUIDVersionUtils.getAllHistoryVersions(originalUUID);
            
            // 2. 查询数据库中存在的历史版本
            java.util.List<PurchaseOrder> historyVersions = new java.util.ArrayList<>();
            
            for (String versionedUUID : historyUUIDs) {
                PurchaseOrder order = purchaseOrderDao.getByPk(versionedUUID);
                if (order != null) {
                    historyVersions.add(order);
                }
            }
            
            // 3. 按版本号排序
            historyVersions.sort((o1, o2) -> UUIDVersionUtils.compareVersions(o1.getDocVersion(), o2.getDocVersion()));
            
            return new JsonResult<java.util.List<PurchaseOrder>>().success(historyVersions);
            
        } catch (Exception e) {
            throw new BizException(ErrorCode.SYS_EXCEPTION.getCode(), "查询历史版本失败：" + e.getMessage());
        }
    }
}


